import dayjs from 'dayjs'
import {getWeightUnits} from "@/pages/RdsViews/components/RelatedName";

/**
 * 格式化当前日期
 * @param {} format
 * @returns
 */
const formatNow = (format = 'YYYY-MM-DD') => {
    return dayjs().format(format)
}
/**
 * 当前日期相加
 * @param startDate
 * @param endDate
 * @param unit 单位：d：天 w：周 m：月 y：年
 * @returns startDate-endDate
 */
const todayAdd = (value, unit = 'd' | 'w' | 'M' | 'y') => {
    return dayjs().add(value, unit || 'd').format('YYYY-MM-DD');
}

const dateAdd = (value, date, unit = 'd' | 'w' | 'M' | 'y') => {
    return dayjs(date).clone().add(value, unit || 'd').format('YYYY-MM-DD')
}

/**
 * 日期差
 * @param date1
 * @param date2
 * @param unit 单位：d：天 w：周 m：月 y：年
 * @returns date1-date
 */
const dateDiff = (date1, date2, unit = 'd' | 'w' | 'm' | 'y') => {
    return dayjs(date1).diff(dayjs(date2), unit || 'd')
}

/**
 * 获取上月第一天日期
 * @returns
 */
const getFirstDayOfPreviousMonth = () => {
    const today = new Date();
    const currentMonth = today.getMonth();
    today.setMonth(currentMonth - 1);
    today.setDate(1);
    const year = today.getFullYear();
    const month = (today.getMonth() + 1).toString().padStart(2, '0');
    const day = today.getDate().toString().padStart(2, '0');

    return `${year}-${month}-${day}`;
}

// 定义一个对象，包含条码前缀码与国家/地区的对应关系
const barcodePrefixes = {
    China: ['69','20', '21', '22', '23', '24', '25', '26', '27', '28', '29']
    // 添加更多国家和地区的前缀码
};

const isDomesticBarcode = (barcode) => {
    const prefix = barcode.substring(0, 2); // 取条码的前两位
    return barcodePrefixes.China.includes(prefix); // 检查条码前缀是否在中国国内条码前缀列表中
};

/**
 * 将 16 进制颜色转换为 RGBA 字符串。
 * @param {string} hex - 16 进制颜色字符串。
 * @returns {string | null} - RGBA 字符串或 null。
 */
const hexToRgb = (hex: string): string | null =>  {
    const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, (m, r, g, b) => {
        return r + r + g + g + b + b;
    });

    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    if (result) {
        const r = parseInt(result[1], 16);
        const g = parseInt(result[2], 16);
        const b = parseInt(result[3], 16);

        return `rgba(${r}, ${g}, ${b}, 0.05)`;
    }

    return null;
}

const hexToRgbToLinear = (hex: string): string | null =>  {
    const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, (m, r, g, b) => {
        return r + r + g + g + b + b;
    });

    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    if (result) {
        const r = parseInt(result[1], 16);
        const g = parseInt(result[2], 16);
        const b = parseInt(result[3], 16);

        return `linear-gradient(135deg, rgba(${r}, ${g}, ${b}, 0.08) 0%, rgba(${r}, ${g}, ${b}, 0.16) 100%)`;
    }

    return null;
}

/**
 * 分组数据
 * @param list
 * @param keys
 * @returns
 */
const groupBy = <T>(list: T[], keys: string[]): {
    keys: any,
    groups: T[],
    indexs: number[]
}[] => {

    const mapKey = (row: T) => keys.map(key => row[key]).join('_')
    const reduceKeyObject = (row: T) => keys.reduce((pre, key) => ({
        ...pre,
        [key]: row[key]
    }), {})

    const groups = list.reduce((ubc, u, index) => {
        const groupKey = mapKey(u);
        const keyObject = reduceKeyObject(u);
        return ({
            ...ubc,
            [groupKey]: {
                keys: keyObject,
                groups: [...(ubc[groupKey]?.groups || []), u],
                indexs: [...(ubc[groupKey]?.indexs || []), index + 1]
            },
        })
    }, {}) as any;

    return Object.keys(groups).map(key => groups[key])

}

export {
    formatNow,
    todayAdd,
    dateAdd,
    dateDiff,
    getFirstDayOfPreviousMonth,
    isDomesticBarcode,
    hexToRgb,
    hexToRgbToLinear,
    groupBy,
}
